package com.jcli.jb51_net.article._198498_实现基于UDP协议网络Socket编程;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPServer {
    private DatagramSocket socket;

    public UDPServer(String serverIPAddress, int port) throws IOException {
        this.socket = new DatagramSocket(port);
    }

    public DatagramPacket udpReceive() throws IOException {
        DatagramPacket receive;
        byte[] dataR = new byte[1024];
        receive = new DatagramPacket(dataR, dataR.length);
        socket.receive(receive);
        return receive;
    }

    public void udpSend(String msg, InetAddress ipRemote, int portRemote) throws IOException {
        DatagramPacket sendPacket;
        byte[] dataSend = msg.getBytes();
        sendPacket = new DatagramPacket(dataSend, dataSend.length, ipRemote, portRemote);
        socket.send(sendPacket);
    }

    public void service() throws IOException {
        System.out.println("服务器启动在监听 " + socket.getLocalPort() + " 端口。");
        System.out.println("服务器创建成功，IP：" + socket.getLocalAddress().getHostAddress() +
                "，端口号：" + socket.getLocalPort());
        while (true) {
            DatagramPacket receivePacket = udpReceive();

            // Extract data and perform necessary actions
            String receivedMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());
            System.out.println("Received message: " + receivedMessage);

            // Implement your logic here based on received message

            // Example: Reply to client
            InetAddress clientAddress = receivePacket.getAddress();
            int clientPort = receivePacket.getPort();
            String replyMessage = "Server: Message received!";
            udpSend(replyMessage, clientAddress, clientPort);

            // Check for termination message from client
            if (receivedMessage.equals("bye")) {
                System.out.println("Client disconnected. Closing server.");
                break; // Exit the loop to end the service
            }
        }
        socket.close();
    }

    public static void main(String[] args) {
        try {
            String serverIPAddress = null; // 设置默认 IP 地址
            // serverIPAddress = "127.0.0.1"; // 设置默认 IP 地址
            int serverPort = 9876; // 设置默认端口号

            if (args.length >= 2) {
                serverIPAddress = args[0]; // 从命令行参数获取 IP 地址
                serverPort = Integer.parseInt(args[1]); // 从命令行参数获取端口号
            }

            UDPServer server = new UDPServer(serverIPAddress, serverPort);
            server.service();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
